import { onActivated, onDeactivated, watch } from 'vue'
import type { WatchCallback, WatchOptions, WatchStopHandle } from 'vue'

// export declare function watch<T extends MultiWatchSources, Immediate extends Readonly<boolean> = false>(sources: [...T], cb: WatchCallback<MapSources<T, false>, MapSources<T, Immediate>>, options?: WatchOptions<Immediate>): WatchStopHandle;

// export declare function watch<T extends Readonly<MultiWatchSources>, Immediate extends Readonly<boolean> = false>(source: T, cb: WatchCallback<MapSources<T, false>, MapSources<T, Immediate>>, options?: WatchOptions<Immediate>): WatchStopHandle;

// export declare function watch<T, Immediate extends Readonly<boolean> = false>(source: WatchSource<T>, cb: WatchCallback<T, Immediate extends true ? T | undefined : T>, options?: WatchOptions<Immediate>): WatchStopHandle;

// export declare function watch<T extends object, Immediate extends Readonly<boolean> = false>(source: T, cb: WatchCallback<T, Immediate extends true ? T | undefined : T>, options?: WatchOptions<Immediate>): WatchStopHandle;

/**
 * 适用于 keep-alive 环境的 watch 钩子，可以同时处理 onActivated 钩子函数
 * @param source 监听的对象，同原 watch 传递
 * @param cb 监听变化执行的回调，同原 watch 传递
 * @param options watch 的配置项，同原 watch 传递，这里需要注意，如果需要在 onActivated 时执行回调，传递 immediate: true 即可
 * @return WatchStopHandle
 */
export default (source: any, cb: WatchCallback, options?: WatchOptions): WatchStopHandle => {
    let destroyWatch = null
    onActivated(() => {
        destroyWatch = watch(source, cb, options)
    })
    onDeactivated(() => {
        destroyWatch()
    })
    return destroyWatch
}
